# 导入需要的模块
import matplotlib.pyplot as plt
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score  # 导入交叉验证模块

# 数据处理
x = np.array([[19, 30], [30, 40], [39, 47], [40, 52], [47, 50], [50, 55], [60, 60], [62, 65], [73, 70], [75, 82], [77, 85], [90, 95], [92, 90]])
y = np.array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1])
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)

# k取不同值的情况下，模型的预测误差率计算
k_range = range(2, 11)  # 设置k值的取值范围
k_error = []            # 保存预测误差率的数组

#计算每隔k值所对应的误差率
#for k in k_range:
#    model = KNeighborsClassifier(n_neighbors=k)
#    scores = cross_val_score(model, x, y, cv=5, scoring='accuracy')
#    k_error.append(1-scores.mean())

# 画图，x轴表示k的取值，y轴表示预测误差率
#plt.rcParams['font.sans-serif'] = 'SimHei'
#plt.plot(k_range, k_error, 'r-')
#plt.xlabel('k的取值')
#plt.ylabel('预测误差率')
#plt.show()

#样本测试
pred_x=[[85,65]]

model1 = KNeighborsClassifier(5)
model1.fit(x_train,y_train)
pred1 = model1.predict(pred_x)
print(f"当k=5时，预测样本的分类结果为：{pred1}")

model1 = KNeighborsClassifier(7)
model1.fit(x_train,y_train)
pred1 = model1.predict(pred_x)
print(f"当k=7时，预测样本的分类结果为：{pred1}")